# coding=utf-8
from __future__ import print_function
from django.shortcuts import render, redirect
from django.views import View
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import *
from django.core.urlresolvers import reverse


from .forms import *

# Create your views here.


class UserLoginView(View):
    template_name = 'accounts/login.html'
    error_template = 'accounts/error.html'

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name)

    def post(self, request, *args, **kwargs):
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('main'))
        else:
            return HttpResponse('用户不存在或禁用')


class CreateUserView(View):

    template_name = 'accounts/register.html'
    error_template = 'accounts/error.html'

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name)

    def post(self, request, *args, **kwargs):
        form = CreateUserForm(request.POST)
        if form.is_valid():
            try:
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = User.objects.create_user(username=username, password=password)
                user.save()
                return HttpResponseRedirect(reverse('set_profile'))
            except BaseException:
                return HttpResponse('用户名已经存在')
        else:
            errors = form.errors.as_json()
            return render(request, self.error_template, {'errors': errors})


def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('user_login'))
